package com.ocean.redisson.lock;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @className: RedisLock
 * @description: TODO
 * @author: lxq
 * @date: 2021/4/17
 **/
@Component
public class RedisLock {
    private final static Logger LOGGER = LoggerFactory.getLogger(RedisLock.class);
    @Autowired
    private RedissonClient redisson;

    public void doSomethingWithLock() {
        RLock lock = redisson.getLock("lockName");
        try{
            //尝试加锁，最多等待2秒，上锁以后20秒自动解锁,故意把解锁时间设置长
            boolean res = lock.tryLock(2, 20, TimeUnit.SECONDS);
            if(res){ //成功
                //处理业务
                LOGGER.info("lock success");
                LOGGER.info("do something");
                Thread.sleep(1000*10);//模拟业务处理10s
                LOGGER.info("do complete");
            }else{
                LOGGER.info("not allow to do something");
            }
        } catch (InterruptedException e) {
            LOGGER.error("InterruptedException e.getMessage():{}",e.getMessage());
            e.printStackTrace();
        } finally {
            if(lock.isLocked()){ // 是否还是锁定状态
                LOGGER.info("prepare to unlock");
                if(lock.isHeldByCurrentThread()){ // 是否是当前执行线程的锁
                    lock.unlock(); // 释放锁
                    LOGGER.info("unlock success");
                }else{
                    LOGGER.info("not locked by current thread");
                }
            }
        }
    }



    public void lockTest(){
        RLock lock = redisson.getLock("lockName");
        try{
            //尝试加锁，最多等待2秒，上锁以后20秒自动解锁,故意把解锁时间设置长
            lock.lock();
            LOGGER.info("lock success");
            LOGGER.info("do something");
            Thread.sleep(1000*10);//模拟业务处理31s
            LOGGER.info("do complete");
        } catch (InterruptedException e) {
            LOGGER.error("InterruptedException e.getMessage():{}",e.getMessage());
            e.printStackTrace();
        } finally {
            if(lock.isLocked()){ // 是否还是锁定状态
                LOGGER.info("prepare to unlock");
                if(lock.isHeldByCurrentThread()){ // 是否是当前执行线程的锁
                    lock.unlock(); // 释放锁
                    LOGGER.info("unlock success");
                }else{
                    LOGGER.info("not locked by current thread");
                }
            }
        }
    }
}
